//
//  JNCardSDKMytools.m
//  7UGame
//
//  Created by 111 on 2017/2/14.
//  Copyright © 2017年 111. All rights reserved.
//

#import "JNCardSDKMytools.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import "PGNetworkHelper+Synchronously.h"
#import <FTIndicator/FTIndicator.h>
static int t_count;
@implementation JNCardSDKMytools

+ (void)requestStringByPostUrl:(NSString *)url parameter:(NSDictionary *)parameter success:(SuccessBlock)aSuccess fail:(FailBlock)aFail
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPBody = data;

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            //没有错误，返回正确；
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString * msg = dict[@"msg"];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * flag =[msg isKindOfClass:[NSNull class]]?@"":msg;
                if ([flag containsString:@"无效的请求:"] && flag.length > 6) {
                    flag = [flag stringByReplacingOccurrencesOfString:@"无效的请求:" withString:@""];
                    [self sendNotifyWithLoginOut:flag];
                }else if([flag containsString:@"无效的请求"] && (flag.length == 6||flag.length==5)){
                    [self sendNotifyWithLoginOut:@"登录超时"];
                }else if ([flag containsString:@"F104:"]) {
                    flag = [flag stringByReplacingOccurrencesOfString:@"F104:" withString:@""];
                    [self sendNotifyWithLoginOut:flag];
                }else{
                    if (aSuccess) {
                        aSuccess(dict);
                    }
                }
            });
        }else{
            //出现错误；
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                NSDictionary * dic = error.userInfo;
                NSString * errorStr = dic[@"NSDebugDescription"];
                if ([errorStr containsString:@"JSON text did not start with array or object and option to allow fragments not set"]) {
                    [self sendNotifyWithLoginOut:@"登录超时"];
                }else{
                    aFail ? aFail(error) : nil;
                }
            });
        }
    }];
    [dataTask resume];

}

+(void)sendNotifyWithLoginOut:(NSString *)warnStr{
    if(t_count>0){
        return;
    }
    t_count ++ ;
    HDAlertView *alertView = [HDAlertView alertViewWithTitle:@"" andMessage:warnStr];
    [alertView addButtonWithTitle:@"确定" type:HDAlertViewButtonTypeDefault handler:^(HDAlertView *alertView) {
        t_count = 0;
        NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
        NSNotification * message = [[NSNotification alloc]initWithName:LoginOutByOtherLogin object:self userInfo:nil];
        [center postNotification:message];
    }];
    alertView.buttonFont = [UIFont systemFontOfSize:[UIFont buttonFontSize]];
    [alertView show];
}

+(NSString *)getMD5code:(NSString *)pswStr{
    NSString *resultStr = nil;//加密后的结果
    const char *cStr = [pswStr UTF8String];//指针不能变，cStr指针变量本身可以变化
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    resultStr = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                 result[0], result[1], result[2], result[3],
                 result[4], result[5], result[6], result[7],
                 result[8], result[9], result[10], result[11],
                 result[12], result[13], result[14], result[15]
                 ];
    return resultStr;
}
+(NSString*)getCurrentTimestamp{
    //获取系统当前的时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
//    NSDate * dat = [self getBeiJingTime];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSInteger newA = a;
    NSString * timeString = [NSString stringWithFormat:@"%ld", (long)newA];
    return timeString;
}
+ (NSString *)timeStampTotime:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate* date =[NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
+(NSDate *)getCurrentDate{
    //以下为准确时间
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}

//字符串转日期
+(NSDate*)dateStrToDate:(NSString *)dateStr{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date =[dateFormat dateFromString:dateStr];
    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    return date2;
}
+(NSDate*)dateStrToDate:(NSString *)dateStr withFormat:(NSString*)format{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:[NSString stringWithFormat:@"yyyy-%@ 00:00:00",format]];
    NSDate *date =[dateFormat dateFromString:dateStr];
    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    return date2;
}
+(NSString *)dateToDateStr:(NSDate*)date{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date2 = [date dateByAddingTimeInterval:-8 * 60 * 60];
    NSString *currentDateStr = [dateFormat stringFromDate:date2];
    return currentDateStr;
}


+(NSString *)numberToMoneyFormatter:(long)num{
    NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString * newNumber = [formatter stringFromNumber:[NSNumber numberWithLong:num]];
    return newNumber;
}

//消息弹窗
+(void)warnText:(NSString *)str status:(JNCardSDKNoticeType)typeP{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (typeP == JNCardSDKCommon) {
            //感叹号
            [FTIndicator showInfoWithMessage:str userInteractionEnable:NO];
        }else if (typeP == JNCardSDKSuccess){
            //success
            [FTIndicator showSuccessWithMessage:str];
        }else if(typeP == JNCardSDKToast){
            [FTIndicator showInfoWithMessage:str];
        }else{
            //error
            [FTIndicator showErrorWithMessage:str];
        }
    });
    
}

//日期大小比较
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //stringFromDate这个方法加了八小时
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    //dateFromString这个方法减了八小时，这狗日的
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
//    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result ==NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

+(NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3)){
        return 28;
    }
    if(year % 400 == 0)
        return 29;
    if(year % 100 == 0)
        return 28;
    return 29;
}

+(NSString *)getBeiJingTime{
//    NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
//    NSString * userName = [def objectForKey:@"username"];
//    if (KHNumber(userName,[def objectForKey:@"getIpStatue"])) {
//        __block NSDictionary * dic = [NSDictionary new];
//        [SVProgressHUD show];
//        NSString * url = [JNCardSDKWorkUrl returnURL:Interface_For_GetServerTime];
//        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//        [LCNetworking getWithURL:url Params:nil success:^(id responseObject) {
//            dic = responseObject;
//            [SVProgressHUD dismiss];
//            dispatch_semaphore_signal(semaphore);
//        } failure:^(NSString *error) {
//            [SVProgressHUD dismiss];
//            dispatch_semaphore_signal(semaphore);
//        }];
//        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//        NSString * bjStr = dic[@"data"];
//        return bjStr;
//    }else{
//        NSString * time = [self timeStampTotime:[self getCurrentTimestamp]];
//        return time;
//    }
    NSString * time = [self timeStampTotime:[self getCurrentTimestamp]];
    return time;
}
+(UIColor*)mostColor:(UIImage*)image{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(image.size.width, image.size.height);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:0.75];//([MaxColor[3] intValue]/255.0f)
     /*
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char rgba[4];
    CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), image.CGImage);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    if(rgba[3] > 0) {
        CGFloat alpha = ((CGFloat)rgba[3])/255.0;
        CGFloat multiplier = alpha/255.0;
        return [UIColor colorWithRed:((CGFloat)rgba[0])*multiplier green:((CGFloat)rgba[1])*multiplier blue:((CGFloat)rgba[2])*multiplier alpha:alpha];
    }else {
        return [UIColor colorWithRed:((CGFloat)rgba[0])/255.0 green:((CGFloat)rgba[1])/255.0 blue:((CGFloat)rgba[2])/255.0 alpha:((CGFloat)rgba[3])/255.0];
    }
     */
}
+(NSString*)returnDecimalNumStr:(NSString*)numStr{
    NSString *doubleString  = [NSString stringWithFormat:@"%lf", [numStr doubleValue]];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}

+(BOOL)IsChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }        
    }
    return NO;
}

+(UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
@end
